package cn.zpro.jeecg.mvc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.zpro.jeecg.mvc.service.MvcService;

public class MvcFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;
		String actionName = "";
		String acionMethod = "";
		String currentURL = request.getRequestURI();// 取得根目录所对应的绝对路径:
		String targetURL = currentURL.substring(currentURL.indexOf("/", 1)+1,
				currentURL.length()); // 截取到当前文件名用于比较
		if (targetURL.contains("!")) {
			String[] tags = targetURL.split("!");
			actionName = tags[0];
			acionMethod = tags[1];
		}
		actionName = actionName.replace("///", "");
		acionMethod = acionMethod.replace(".do", "");

		// 和Xml配置文件中比对一下
		MvcService mvcSe = new MvcService();
		String url = mvcSe.findUrlByAnnotation(actionName,acionMethod);

		System.out.println(url);
		//跳转到登陆页面 index.jsp在webRoot根目录下
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response); 
		return;
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
